package top.dancun.easuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.dancun.common.utils.Constant;
import top.dancun.common.utils.PageUtils;
import top.dancun.common.utils.Query;
import top.dancun.easuser.dao.MenuDao;
import top.dancun.easuser.entity.MenuEntity;
import top.dancun.easuser.service.MenuService;

import java.util.*;


@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuDao, MenuEntity> implements MenuService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MenuEntity> page = this.page(
                new Query<MenuEntity>().getPage(params),
                new QueryWrapper<MenuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<MenuEntity> getUserMenuList(String userId) {
       if(userId == Constant.SUPER_ADMIN){
           return getMenuList(null,Constant.OnlyMenu);
       }else {
           List<Long> menuIdList = baseMapper.queryUserAllMenuId(userId);
           return getMenuList(menuIdList,Constant.OnlyMenu);
       }
    }

    @Override
    public List<MenuEntity> getMenuAndPermissList() {
        return getMenuList(null,false);
    }

    @Override
    public List<MenuEntity> getMenuList() {
        return getMenuList(null,Constant.OnlyMenu);
    }

    private List<MenuEntity> getMenuList(List<Long> menuIdList,Boolean OnlyMenu){
        List<MenuEntity> menus = this.lambdaQuery().in(Objects.nonNull(menuIdList),MenuEntity::getMenuId,menuIdList ).in(OnlyMenu,MenuEntity::getType,0,1).orderByAsc(MenuEntity::getOrderNum).list();
        HashMap<Long,MenuEntity> menuMap = new HashMap<>();
        for(MenuEntity menu : menus){
            menuMap.put(menu.getMenuId(),menu);
        }
        //迭代器组装菜单
        Iterator<MenuEntity> iterator = menus.iterator();

        while (iterator.hasNext()){
            MenuEntity menu = iterator.next();
            MenuEntity parent = menuMap.get(menu.getParentId());
            if (Objects.nonNull(parent)) {
                //将当前节点放置于父节点的子菜单的集合里
                parent.getList().add(menu);
                //从menus删除此节点
                iterator.remove();
            }
        }

        return menus;
    }


}